<template>
    <div>
        <div id="echart" style="width: 300px; height: 300px;"></div>
    </div>
</template>
<script>
import * as echarts from 'echarts';
export default {
    name: 'echarts',
    data() {
        return {
            datas: [
                {
                    month: '2024-02',
                    type: '拖拉机',
                    price: 65
                },
                {
                    month: '2024-02',
                    type: '无人机',
                    price: 40
                },
                {
                    month: '2024-03',
                    type: '拖拉机',
                    price: 30
                },
                {
                    month: '2024-03',
                    type: '无人机',
                    price: 75
                },
                {
                    month: '2024-04',
                    type: '无人机',
                    price: 201
                }
            ]
        }
    },
    mounted() {
        this.initEchart()
    },
    methods: {
        initEchart() {
            var myChart = echarts.init(document.getElementById('echart'));
            var options = {
                title: {
                    text: 'Stacked Line'
                },
                tooltip: {
                    trigger: 'axis'
                },
                legend: {
                    data: []
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true
                },
                toolbox: {
                    feature: {
                        saveAsImage: {}
                    }
                },
                xAxis: {
                    type: 'category',
                    boundaryGap: false,
                    data: []
                },
                yAxis: {
                    type: 'value'
                },
                series: []
                }
            // 提取月份并去重
            let list = [...new Set(this.datas.map(item => item.month))];
            options.xAxis.data = list
            // 根据type分组价格
            var groupedData = {};
            this.datas.forEach(item => {
                var type = item.type;
                if (!groupedData[type]) {
                    groupedData[type] = [];
                }
                groupedData[type].push(item.price);
            });
            options.legend.data = Object.keys(groupedData)
            // 赋值给图标
            var list1 = Object.keys(groupedData).map(type => ({
                name: type,
                data: groupedData[type],
                type: 'line',
                stack: 'Total',
            }))
            console.log(list1)
            options.series = list1
            myChart.setOption(options)
        }
    }
}
</script>
<style lang="scss" scoped>
</style>